package org.leetcode.middle.leetcode40;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class Solution {

    int sum = 0;
    List<List<Integer>> res = new ArrayList<>();

    LinkedList<Integer> path = new LinkedList<>();

    boolean[] used;

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        used = new boolean[candidates.length];
        Arrays.fill(used, false);

        backtracking(candidates, target, 0);
        return res;
    }

    private void backtracking2(int[] candidates, int target, int sum, int index) {
        if (sum > target) {
            return;
        }
        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }

        for (int i = index; i < candidates.length; i++) {

            //如果当前的元素和上一步的元素相同
            //used[i-1]为true的含义：在当前递归路径中前一个元素被使用
            //used[i-1]为false的含义：在当前递归路径中前一个元素没有被使用，但是在前面的递归中被使用
            if (i>0 && candidates[i]==candidates[i-1] && !used[i-1]){
                continue;
            }

            sum += candidates[i];
            path.add(candidates[i]);
            //对同一层的节点去重
            used[i]=true;

            backtracking2(candidates, target, sum, i + 1);

            sum -= candidates[i];
            path.remove(path.size() - 1);
            used[i]=false;
        }
    }

    private void backtracking(int[] candidates, int target, int start) {
        if (sum > target) {
            return;
        }

        if (path.size() == candidates.length && sum != target) {
            return;
        }

        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }

        for (int i = start; i < candidates.length; i++) {
            sum = sum + candidates[i];
            path.add(candidates[i]);
            backtracking(candidates, target, i + 1);

            sum = sum - candidates[i];
            path.removeLast();

            //去重
            while (i < candidates.length - 1 && candidates[i] == candidates[i + 1])
                i++;
        }

    }

}
